package com.caiheng.api.util;

import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClient;
import com.aliyun.oss.OSSClientBuilder;
import com.aliyun.oss.model.PutObjectResult;
import com.obs.services.ObsClient;

import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.io.InputStream;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;
import java.util.Date;

public class OssUtil {

    // endpoint以杭州为例，其它region请按实际情况填写。simple-mall.oss-cn-beijing.aliyuncs.com
    private static final String endpoint = "http://oss-cn-hangzhou.aliyuncs.com";
    private static final String accessKeyId = "LTAI5tFMChM8vZoNHi1kX5xs";
    private static final String accessKeySecret = "j9SK49ar6pqAUyW9PegrMDTYtXqIWt";
    private static final String bucketName = "yuedou";




    private static final String endpointObs = "http://obs.cn-north-9.myhuaweicloud.com";
    private static final String accessKeyIdObs = "HPUARHTZGR5VUUX5JADZ";
    private static final String accessKeySecretObs = "hVP7cXcZzbLgNbEMeX23ZGG0Cic5IyIGRLtwwLCY";
    private static final String bucketNameObs = "caihengyun";



    public static final int TYPE_PRODUCT_PHOTOS = 1;//图片文件夹
    public static final int TYPE_MER_PHOTOS = 2;//图片文件夹
    public static final int TYPE_REPAIR_RECORD_PHOTOS = 3;//图片文件夹
    public static final  int TYPE_EVENT_PHOTOS = 4;
    public static final  int TYPE_ORDER_REFUND_IMGS = 5;
    public static final  int TYPE_ORDER_REFUND_BALANCE_IMGS = 6;
    public static final  int TYPE_ORDER_INFO_VERIFYCODE_IMGS = 7;
    public static final  int TYPE_TERMINAL_RECORD_PHOTOS = 8;

    public static final  int TYPE_SURVEY_PHOTOS = 9;
    public static final int TYPE_COMMONINFO = 10;//充电设备
    public static final  int TYPE_USER_QRCODE_PHOTOS = 11;
    public static final  int TYPE_ORDER_APPRAISE_IMGS = 12;
    public static final int TYPE_ESTATE_CHAT = 13;//充电设备
    public static final int TYPE_USER_FACE = 16;//头像
    public static final int TYPE_EXAMINE_APPROVE = 17;//审批
    public static final int TYPE_ATTENDANCE = 18;//考勤打卡
    public static final int TYPE_ASSET_RECORD = 19;//资产
    public static final int TYPE_PAYSLIP = 20;//工资条
    public static final int TYPE_CALL_RECORD_PHOTOS = 21;//客服呼叫记录图片


    private static final String PRODUCT_IMG_PREFIX  = "product/";
    private static final String MER_IMG_PREFIX  = "shop/";
    private static final String USER_FACE_PREFIX  = "user_face/";

    private static final String EVENT_PREFIX  = "event/";

    private static final String SURVEY_PREFIX  = "survey/";
    private static final String REPAIR_RECORD_IMG_PREFIX  = "repair/";
    private static final String ORDER_APPRAISE_IMG_PREFIX  = "order/";
    private static final String ORDER_REFUND_IMGS_PREFIX  = "refund/";
    private static final String ORDER_REFUND_BALANCE_IMGS_PREFIX  = "balance/";
    private static final String ORDER_INFO_VERIFYCODE_IMGS_PREFIX  = "verify/";
    private static final String TERMINAL_RECORD_IMG_PREFIX  = "te_record/";
    private static final String COMMONINFO_IMG_PREFIX  = "commonInfo/";
    private static final String USER_QRCODE_IMG_PREFIX  = "userQr/";
    private static final String ESTATE_CHAT_IMG_PREFIX  = "chat/";
    private static final String EXAMINE_APPROVE_IMG_PREFIX  = "examine/";

    private static final String ATTENDANCE_IMG_PREFIX  = "attendance/";
    private static final String ASSET_RECORD_IMG_PREFIX  = "asset/record/";
    private static final String PAYSLIP_IMG_PREFIX  = "payslip/";
    private static final String CALL_RECORD_IMG_PREFIX  = "callrecord/";
    private static final int validity = 60 * 1000;


    /**
     * 获取  上传图片的 路径前缀
     * @param upload_type
     * @return
     */
    public static String getUploadPrefix(int upload_type){
        String prefix = null;
        switch (upload_type) {
            case TYPE_PRODUCT_PHOTOS:
                prefix = PRODUCT_IMG_PREFIX;
                break;
            case TYPE_MER_PHOTOS:
                prefix = MER_IMG_PREFIX;
                break;
            case TYPE_ORDER_APPRAISE_IMGS:
                prefix = ORDER_APPRAISE_IMG_PREFIX;
                break;
            case TYPE_EVENT_PHOTOS:
                prefix = EVENT_PREFIX;
                break;
            case TYPE_REPAIR_RECORD_PHOTOS:
                prefix = REPAIR_RECORD_IMG_PREFIX;
                break;
            case TYPE_ORDER_REFUND_IMGS:
                prefix = ORDER_REFUND_IMGS_PREFIX;
                break;
            case TYPE_ORDER_REFUND_BALANCE_IMGS:
                prefix = ORDER_REFUND_BALANCE_IMGS_PREFIX;
                break;
            case TYPE_ORDER_INFO_VERIFYCODE_IMGS:
                prefix = ORDER_INFO_VERIFYCODE_IMGS_PREFIX;
                break;
            case TYPE_TERMINAL_RECORD_PHOTOS:
                prefix = TERMINAL_RECORD_IMG_PREFIX;
                break;
            case TYPE_COMMONINFO:
                prefix = COMMONINFO_IMG_PREFIX;
                break;
            case TYPE_USER_QRCODE_PHOTOS:
                prefix = USER_QRCODE_IMG_PREFIX;
                break;
            case TYPE_ESTATE_CHAT:
                prefix = ESTATE_CHAT_IMG_PREFIX;
                break;
            case TYPE_USER_FACE:
                prefix = USER_FACE_PREFIX;
                break;
            case TYPE_EXAMINE_APPROVE:
                prefix = EXAMINE_APPROVE_IMG_PREFIX;
                break;
            case TYPE_SURVEY_PHOTOS:
                prefix = SURVEY_PREFIX;
                break;
            case TYPE_ATTENDANCE:
                prefix = ATTENDANCE_IMG_PREFIX;
                break;
            case TYPE_ASSET_RECORD:
                prefix =  ASSET_RECORD_IMG_PREFIX;
                break;
            case TYPE_PAYSLIP:
                prefix = PAYSLIP_IMG_PREFIX;
                break;
            case TYPE_CALL_RECORD_PHOTOS:
                prefix = CALL_RECORD_IMG_PREFIX;
                break;

        }
        return prefix;
    }


    public static void main(String args[]){
        String url = "/article/1/2c1157af-7612-43bd-b34c-e928338ab6a9.png";
        url = url.substring(1,url.length());
        boolean bl = deleteObjByKey(url);
        if(bl){
            System.out.println("删除成功");
        }else{
            System.out.println("删除失败");
        }
    }

    /**
     * 上传文件
     * @param inputStream 要上传的文件流
     * @param fileName 要上传的文件名字
     * @param upload_type 要上传的文件类型
     */
    public static boolean upload(InputStream inputStream,String fileName,int upload_type) {
        boolean ret = false;
        // 上传文件流
        if (inputStream!=null){
            OSSClient ossClient = new OSSClient(endpoint, accessKeyId, accessKeySecret);
            //inputStream = new FileInputStream("/Users/ran/Desktop/会议记录0521.txt");
            String prefix = getUploadPrefix(upload_type);
            if (prefix!=null){
                PutObjectResult putObjectResult = ossClient.putObject(bucketName, prefix + fileName, inputStream);
                String eTag = putObjectResult.getETag();
                System.out.println("upload "+fileName +"-->"+ eTag);
            }
            // 关闭client。
            ossClient.shutdown();
        }
        System.out.println("upload "+fileName +"是否成功-->"+ (ret?"YES":"NO"));
        return ret;
    }

    /**
     * 上传文件
     * @param inputStream 要上传的文件流
     * @param fileName 要上传的文件名字
     */
    public static boolean upload(InputStream inputStream,String fileName) {
        boolean ret = false;
        // 上传文件流
        if (inputStream!=null){
            OSSClient ossClient = new OSSClient(endpoint, accessKeyId, accessKeySecret);
            //inputStream = new FileInputStream("/Users/ran/Desktop/会议记录0521.txt");
//            String prefix = getUploadPrefix(upload_type);
            if (fileName!=null){
                PutObjectResult putObjectResult = ossClient.putObject(bucketName, fileName, inputStream);
                String eTag = putObjectResult.getETag();
                System.out.println("upload "+fileName +"-->"+ eTag);
            }
            // 关闭client。
            ossClient.shutdown();
        }
        System.out.println("upload "+fileName +"是否成功-->"+ (ret?"YES":"NO"));
        return ret;
    }



    /**
     * 上传文件
     * @param inputStream 要上传的文件流
     * @param fileName 要上传的文件名字
     * @param upload_type 要上传的文件类型
     */
    public static boolean uploadObs(InputStream inputStream, String fileName, int upload_type) {
        boolean ret = false;
        // 上传文件流
        if (inputStream != null){
            ObsClient ossClient = new ObsClient(accessKeyIdObs, accessKeySecretObs, endpointObs);
            //inputStream = new FileInputStream("/Users/ran/Desktop/会议记录0521.txt");
            String prefix = getUploadPrefix(upload_type);
            if (prefix != null){
                System.out.println("上传图片地址：" + prefix + fileName);
                com.obs.services.model.PutObjectResult putObjectResult = ossClient.putObject(bucketNameObs, prefix + fileName, inputStream);
                String eTag = putObjectResult.getEtag();
                System.out.println("upload "+fileName +"-->"+ eTag);
            }
            // 关闭client。
            try {
                ossClient.close();
            } catch (IOException e) {
                throw new RuntimeException(e);
            }
        }
        System.out.println("upload "+fileName +"是否成功-->"+ (ret?"YES":"NO"));
        return ret;
    }



    /**
     * 根据key获取url
     * @param object_key
     * @return
     */
    public static String getSignUrl(String object_key){
        //创建OSSClient实例
        OSSClient ossClient = new OSSClient(endpoint, accessKeyId,accessKeySecret);
        //validity url的有效期
        URL url = ossClient.generatePresignedUrl(bucketName, object_key, new Date(new Date().getTime()+validity));;
        //关闭client
        ossClient.shutdown();
        return url==null?null:url.toString();
    }


    /**
     * 删除文件
     * @param objKey
     * @return
     */
    public static boolean deleteObjByKey(String objKey) {
        boolean ret = false;
        //创建OSSClient实例
        OSS ossClient = new OSSClientBuilder().build(endpoint, accessKeyId,accessKeySecret);
        ossClient.deleteObject(bucketName,objKey);
        // Object是否存在。
        ret = ossClient.doesObjectExist(bucketName, objKey);
        ossClient.shutdown();
        return !ret;
    }

    public static BufferedImage getImageInfoByUrl(String urlStr){

        try{
            URL url = new URL(urlStr);
            URLConnection urlConnection = url.openConnection();
            int length = urlConnection.getContentLength();
            System.out.print("length: " + length);
            if(length == -1){
                System.out.print("image not exist");
            }else{
                BufferedImage sourceImg = ImageIO.read(url);
                System.out.print("image width:" + sourceImg.getWidth());
                System.out.print("image height:" + sourceImg.getHeight());
                return sourceImg;
            }
        }catch (MalformedURLException e){
//            logger.info("url not right " + e.getMessage(), e);
        } catch (IOException e){
//            logger.info("IOException " + e.getMessage(), e);
        }
        return null;
    }
}
